# Create your views here.
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from rest_framework import viewsets, status, permissions
from rest_framework.authentication import SessionAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler

from users.serializers import EmailSerialier, UserRegSerializer, UserDetailSerializer
from utils.mixins import CustomRetrieveModelMixin, CustomCreateModelMixin, CustomUpdateModelMixin
from utils.response import APIResponse
from utils.send_email import send_code_email

User = get_user_model()


class CustomBackend(ModelBackend):
    """
    自定义用户验证
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = User.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):
                return user
        except Exception:
            return None


class SmsCodeViewset(CustomCreateModelMixin, viewsets.GenericViewSet):
    """
    发送短信验证码
    """
    serializer_class = EmailSerialier

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        email = serializer.validated_data["email"]

        sms_status = send_code_email(email)

        if sms_status:
            return APIResponse(
                status.HTTP_201_CREATED,
                "邮件发送成功！"
            )
        else:
            return APIResponse(
                status.HTTP_400_BAD_REQUEST,
                "邮件发送失败！"
            )


class UserViewset(CustomCreateModelMixin, CustomUpdateModelMixin, CustomRetrieveModelMixin, viewsets.GenericViewSet):
    """
    用户
    """
    serializer_class = UserRegSerializer
    queryset = User.objects.all()
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)

    def get_serializer_class(self):
        if self.action == "retrieve":
            return UserDetailSerializer
        elif self.action == "create":
            return UserRegSerializer

        return UserDetailSerializer

    def get_permissions(self):
        if self.action == "retrieve":
            return [permissions.IsAuthenticated()]
        elif self.action == "create":
            return []

        return []

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)

        re_dict = serializer.data
        payload = jwt_payload_handler(user)
        re_dict["token"] = jwt_encode_handler(payload)
        re_dict["name"] = user.name if user.name else user.username

        headers = self.get_success_headers(serializer.data)
        return APIResponse(
            data_status=status.HTTP_201_CREATED,
            results=re_dict,
            msg='注册成功！',
            headers=headers,
        )

    def get_object(self):
        return self.request.user

    def perform_create(self, serializer):
        return serializer.save()
